package com.geekcode.wol.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
 
public class Arp {
 
	public static List<String>  getIPs(){
		List<String> list = new ArrayList<String>();
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("arp -a");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GB2312")));
            String inline;
            while ((inline = br.readLine()) != null) {
            	list.add(inline);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
	
	public static String getHostnames(String ip){
        System.out.println("正在提取hostname:" + ip);
        String command = "ping -a " + ip;
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inline;
            while ((inline = br.readLine()) != null) {
                if(inline.indexOf("[") > -1){
                    int start = inline.indexOf("Ping ");
                    int end = inline.indexOf("[");
                    return inline.substring(start+"Ping ".length(),end-1);
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
	
	public static String getHostname(String ip){
		System.out.println("正在提取hostname:" + ip);
		InetAddress address = null;
	      try {
	         address = InetAddress.getByName(ip);
	         return address.getHostName();
	      } catch (Exception e) { }
	      return "";
    }
}